/**
 * Created by zlp on 2017-12-19.
 */

var request = require("superagent");
var API = require("./support/const")
var service = require("../../service/log")



//导出excel通用方法，
function exportExcel(req, res, header, params, api, type) {
    request.get(api)
        .set(header)
        .responseType("blob")
        .query({msg: JSON.stringify(params)})
        .end(function (_req, _res) {
            if (_res.status === 200) {
                service.save_user_log({'type': 'getList', 'msg': '导出' + type + '列表'}, req);
            }
            //导出型api, 返回文件流，在_res.body中, 而不在_res.text中
            //_res.body有可能是文件内容，也可能是错误信息
            var buffer = Buffer.from(_res.body);
            if (_res.header["content-type"]) {
                res.setHeader('Content-Type', _res.header["content-type"]);
            }
            if (_res.header["content-disposition"]) {
                res.setHeader('content-disposition', _res.header["content-disposition"]);
            }
            res.end(buffer);
        });
}


/**
 * 合同管理
 * **/

exports.contract = {
    list : function (req, res, next) {
        let _res = res;
        let _req = req;
        let header = {
            token: _req.cookies.token
        };
        let {page_size, page_no, order_column, order_by, condition} = req.body;
        let params = {
            "page_size": page_size || 10,
            "page_no": page_no,
            "order_column": order_column,
            "order_by": order_by,
            "condition": condition
        };
        console.log('============================合同列表====================================');
        console.log(header);
        console.log(JSON.stringify(params));
        console.log(`${API.contract.contract_list}/list`);
        console.log('================================================================');
        request.get(`${API.contract.contract_list}/list`)
            .query({msg: JSON.stringify(params)})
            .set(header)
            .end(function (req, res) {

                if (res.status === 200) {
                    service.save_user_log({'type': 'getList', 'msg': '合同列表'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    single : function (_req, _res, next) {
        let header = {
            token: _req.cookies.token
        };

        let {id} = _req.body;
        request.get(`${API.contract.contract_list}/info/` + id)
            // .query({msg: JSON.stringify(params)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'getId', 'msg': '合同详情'}, _req);
                    _res.json(JSON.parse(res.text))
                }else{
                    _res.json(res)
                }

            });
    },
    add : function (_req, _res, next) {
        let header = {
            token: _req.cookies.token
        };
        request.post(`${API.contract.contract_list}/add`)
            .query({msg: JSON.stringify(_req.body)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'edit', 'msg': '新增合同信息'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    retrieval : function (req, res, next) {
        let _res = res;
        let _req = req;
        let header = {
            token: _req.cookies.token
        };
        let {full_name} = req.body;
        let params = {
            "full_name": full_name
        };
        request.post(`${API.contract.sale_org_name}`)
            .query({msg: JSON.stringify(params)})
            .set(header)
            .end(function (req, res) {

                if (res.status === 200) {
                    service.save_user_log({'type': 'getList', 'msg': '根据客户姓名模糊检索（新增或修改合同信息时）'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    edit : function (_req, _res, next) {
        let header = {
            token: _req.cookies.token
        };
        console.log('============================更新合同信息====================================');
        console.log(header);
        console.log(JSON.stringify(_req.body));
        console.log(`${API.contract.contract_list}/update`);
        console.log('================================================================');
        request.put(`${API.contract.contract_list}/update`)
            .query({msg: JSON.stringify(_req.body)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'edit', 'msg': '更新合同信息'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    remove : function (_req, _res, next) {

        let header = {
            token: _req.cookies.token
        };

        let {id} = _req.body;
        // let params = {
        //     "customer_id": id
        // };

        request.delete(`${API.contract.contract_list}/delete/${id}`)
        // .query({msg: JSON.stringify(params)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'del', 'msg': '删除合同信息'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    export: function (req, res, next) {
        let params = req.body;
        let header = {
            token: req.cookies.token
        };
        let api = API.contract.contract_list + '/export';
        exportExcel(req, res, header, params, api, "导出合同信息");
    },

};


/**
 * 待审核列表
 * **/

exports.pending = {
    list : function (req, res, next) {
        let _res = res;
        let _req = req;
        let header = {
            token: _req.cookies.token
        };
        let {page_size, page_no, order_column, order_by, condition} = req.body;
        let params = {
            "page_size": page_size || 10,
            "page_no": page_no,
            "order_column": order_column,
            "order_by": order_by,
            "condition": condition
        };

        request.get(`${API.contract.pending_list}`)
            .query({msg: JSON.stringify(params)})
            .set(header)
            .end(function (req, res) {
                console.log(res.text)
                if (res.status === 200) {
                    service.save_user_log({'type': 'getList', 'msg': '合同 - 待审核列表'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    agree : function (_req, _res, next) {
        let header = {
            token: _req.cookies.token
        };
        var {id} = _req.body;
        console.log('============================ 审核通过操作 ====================================');
        console.log(header);
        console.log(JSON.stringify(id))
        console.log(API.contract.contract_list + '/agree/' + id)
        console.log('================================================================');
        request.put(`${API.contract.contract_list}/agree/${id}`)
            .query({msg: JSON.stringify(_req.body)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'edit', 'msg': '审核合同 - 审核通过操作'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    },
    refuse : function (_req, _res, next) {
        let header = {
            token: _req.cookies.token
        };
        var {id} = _req.body;
        console.log('============================审核拒绝操作====================================');
        console.log(header);
        console.log(JSON.stringify(id))
        console.log(API.contract.contract_list + '/agree/' + id)
        console.log('================================================================');
        request.put(`${API.contract.contract_list}/refuse`)
            .query({msg: JSON.stringify(_req.body)})
            .set(header)
            .end(function (req, res) {
                if (res.status === 200) {
                    service.save_user_log({'type': 'edit', 'msg': '审核合同 - 审核拒绝操作'}, _req);
                }
                _res.json(JSON.parse(res.text))
            });
    }
};
